<template>
  <!-- 模态框 -->
  <div class="model">
    <!-- 不使用嵌套方式布局，避免后期事件冒泡问题 -->
    <!-- 遮罩层 -->
    <div class="mask" @click="changeShowLoginModal(false)"></div>
    <!-- 登录box -->
    <div class="loginBox">
      <div class="close" @click="changeShowLoginModal(false)"></div>
      <!-- 导航 -->
      <section class="nav">
        <a href="#" :class="{ active: isShowPhone }" @click="isShowPhone = true"
          >手机号登录</a
        >
        |
        <a href="#" :class="{ active: !isShowPhone }" @click="showQR"
          >微信扫码登录</a
        >
      </section>
      <!-- 内容区域 -->
      <div class="content">
        <!-- 手机号登录内容 -->
        <div class="phoneLogin" v-show="isShowPhone">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              class="ipt"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="arr"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              placeholder="请输入验证码"
              class="ipt"
              v-model="code"
            />
            <!-- <button class="btncode" @click="getCode">
              {{ isShowCount ? count + "s" : "获取验证码" }}
            </button> -->
            <!-- 连续点击会触发getCode会创建对个定时器，造成递减混乱问题 -->
            <button class="btncode" @click="getCode" v-show="!isShowCount">
              获取验证码
            </button>
            <button class="btncode" v-show="isShowCount">
              {{ count + "s" }}
            </button>
          </div>
          <div class="row">
            <button class="btnlogin" @click="submitFn">登录</button>
          </div>
        </div>
        <!-- 微信扫码登录内容 -->
        <div class="qrLogin" v-show="!isShowPhone" id="weixin"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
import { SendSMSAPI, PhoneLoginAPI, BinddingAPI } from "@/request/api";
import { validatePhoneNumber } from "@/utils/index";
import loginStatus from "@/store/loginStatus";
export default {
  data() {
    return {
      isShowPhone: true,
      msg: "向右滑动",
      // 背景图数组
      arr: [
        require("../assets/img/service.848ec511.png"),
        require("../assets/img/monad.png"),
      ],
      // 手机号码
      phoneNumber: "",
      // 倒计时数字
      count: 59,
      // 是否显示倒计时
      isShowCount: false,
      code: "",
    };
  },
  methods: {
    ...mapMutations({
      // 方法名："模块名/方法名"
      changeShowLoginModal: "showModal/changeIsShowLoginModal",
      changeIsLogined: "loginStatus/changeIsLogined",
    }),
    ...mapActions({
      asyncChangeIsShowToast: "ShowToast/asyncChangeIsShowToast",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),

    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },

    // 倒计时
    daojishi() {
      this.isShowCount = true;
      let timer = setInterval(() => {
        this.count--;
        if (this.count <= 0) {
          this.count = 59;
          clearInterval(timer);
          this.isShowCount = false;
        }
      }, 1000);
    },
    // 手机号滑块验证
    toVerify() {
      // 1.判断手机号是否正确，不正确提示

      // reg.test(str) 返回true 不存在返回false
      if (!validatePhoneNumber(this.phoneNumber)) {
        // alert("请输入正确的手机号码");
        // this.changeIsShowToast({
        // isshow: true,
        // msg: "请输入正确的手机号码",
        // type: "success",
        // });
        // setTimeout(() => {
        //   this.changeIsShowToast({
        //     isshow: false,
        //   });
        // }, 1500);
        this.asyncChangeIsShowToast({
          isshow: true,
          msg: "请输入正确的手机号码",
          type: "success",
        });
        return;
      }

      // 2.滑块验证码不正确 提示
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        // alert("请滑动验证码");
        this.asyncChangeIsShowToast({
          isshow: true,
          msg: "请滑动验证码",
          type: "success",
        });
        return;
      }
      // 函数默认返回undefined
      return true;
    },
    // 获取验证码
    async getCode() {
      let flag = this.toVerify();
      // console.log(flag);
      if (!flag) return; //不通过不往下执行

      // 3.获取验证码--60s倒计时功能
      // 获取验证码 -- 发请求
      // 倒计时 循环定时器递减数字count
      let res = await SendSMSAPI({
        phone: this.phoneNumber,
      });
      // console.log("发送验证码res:", res);

      if (!res) return;
      alert("发送成功");
      // 调用倒计时
      this.daojishi();
    },
    // 登录
    async submitFn() {
      // 1.手机号不正确
      // 2.滑块不正确提示
      if (!this.toVerify()) return;
      // 3.短信验证码不正确提示
      if (this.code.trim() == "") {
        alert("请输入验证码");
        return;
      }
      // 4发送登录请求 分两种情况 有uuid 就关联微信，没有就普通的手机号码验证登录
      // 手机号码验证登录
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        res = await BinddingAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
          uuid,
        });
      } else {
        res = await PhoneLoginAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
        });
      }

      if (!res) return;
      // 1.提示
      alert("登录成功");
      // 2.存储totken obj["a"] obj.a
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      // 3.关闭登录模态框
      this.changeShowLoginModal(false);
      // 4.topbar中登录状态切换  (修改vue中isLogined为true)
      this.changeIsLogined(true);
      /* 
      1.布局一个购物车按钮
      2，vuex中loginStatus存储一个状态isLogined(是否登录的状态)
      store
        loginStatus
          index.js
      3.根据isLogined来控制购物车按钮是否显示
        本地有token isLogined则为true，本地无token 则为false

      最终效果，刷新后可以是根据本地是否有token来控制是否显示购物车按钮
      */
      uuid && this.$router.push(this.$route.path);
      // uuid && $router.push
      localStorage.removeItem("uuid");

      // 获取用户信息并更新vuex的数据
      this.asyncChangeUserInfo();
    },
    // 微信扫码登录
    showQR() {
      // 点击切换微信扫码登录这一项，并向微信扫码登录
      this.isShowPhone = false;
      // 微信登录第一步：申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9DQoNCi8qIC5pbXBvd2VyQm94IHFyY29kZSB7DQogICAgbWFyZ2luLXRvcDogMjBweDsNCn0gKi8=",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.model {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginBox {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      right: 60px;
      top: 18px;
      width: 22px;
      height: 22px;
      background: url("../assets/img/close.png");
    }
    .nav {
      padding-top: 50px;
      text-align: center;
      a {
        text-decoration: none;
        color: gray;
        &.active {
          color: black;
        }
      }
    }
    .content {
      // background: pink;
      width: 355px;
      height: 300px;
      margin: 10px auto 0;
      // 登录样式
      .phoneLogin {
        .row {
          display: flex;
          margin-bottom: 20px;
          .ipt {
            height: 50px;
            outline: none;
            flex: 1;
            text-indent: 1em;
          }
          .btncode {
            background-color: #0a328e;
            color: #fff;
            margin-left: 10px;
            border: none;
            width: 86px;
          }
          .btnlogin {
            background-color: #0a328e;
            color: #fff;
            height: 50px;
            width: 100%;
            border: none;
          }
        }
      }
      .qrLogin {
        text-align: center;
      }
    }
  }
}
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>